package io.persimmon.core.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {

    /**
     * 将日期转换为指定格式的字符串
     *
     * @param date    要转换的日期
     * @param pattern 日期格式，例如 "yyyy-MM-dd HH:mm:ss"
     * @return 格式化后的日期字符串
     */
    public static String format(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    public static String format(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    /**
     * 将字符串解析为 Date 对象
     *
     * @param dateStr 要解析的日期字符串
     * @param pattern 日期格式，例如 "yyyy-MM-dd HH:mm:ss"
     * @return 解析后的 Date 对象，如果解析失败则返回 null
     */
    public static Date parse(String dateStr, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取当前日期的字符串表示
     *
     * @param pattern 日期格式，例如 "yyyy-MM-dd HH:mm:ss"
     * @return 当前日期的格式化字符串
     */
    public static String getCurrentDate(String pattern) {
        return format(new Date(), pattern);
    }

    public static int getYear(Date date) {
        return Integer.parseInt(format(date, "yyyy"));
    }

    public static int getMonth(Date date) {
        return Integer.parseInt(format(date, "MM"));
    }

    public static int getDay(Date date) {
        return Integer.parseInt(format(date, "dd"));
    }

    public static int getHour(Date date) {
        return Integer.parseInt(format(date, "HH"));
    }

    public static int getMinute(Date date) {
        return Integer.parseInt(format(date, "mm"));
    }

    public static int getSecond(Date date) {
        return Integer.parseInt(format(date, "ss"));
    }

    public static int getMillisecond(Date date) {
        return Integer.parseInt(format(date, "SSS"));
    }

    public static int currentYear() {
        return getYear(new Date());
    }

    public static int currentMonth() {
        return getMonth(new Date());
    }

    public static int currentDay() {
        return getDay(new Date());
    }

    public static int currentHour() {
        return getHour(new Date());
    }

    public static int currentMinute() {
        return getMinute(new Date());
    }

    public static int currentSecond() {
        return getSecond(new Date());
    }

    public static int currentMillisecond() {
        return getMillisecond(new Date());
    }
}
